package com.tzg.iot.http.service;

import com.alibaba.fastjson.JSONObject;
import com.tzg.iot.http.info.HostInfo;
import com.tzg.iot.http.util.HttpClientUtil;
import com.tzg.iot.http.util.TokenUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @author tzg157
 */
public class LoginService {

    private String token;

    /**
     * 基于jwt,所以登录后会返回jwt串
     * @return
     */
    public String login(String user,String password) throws IOException {
        StringBuilder data = new StringBuilder();
        data.append("{").append("\"").append("username").append("\"").append(":").append("\"").append(user).append("\"")
                .append(",\"").append("password").append("\"").append(":").append("\"").append(password).append("\"").append("}");
        System.out.println("data:" + data.toString());
//        InputStream input = HttpClientUtil.post(HostInfo.HOST,HostInfo.PORT,HostInfo.LOGIN_PATH,data.toString());

        InputStream input =
                HttpClientUtil.post(HostInfo.HTTP_PROTOCOL + HostInfo.HOST + ":" + HostInfo.PORT + HostInfo.LOGIN_PATH ,data.toString());
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
        String line = null;
        String result = "";
        while ((line = bufferedReader.readLine()) != null) {
            if(line.contains("token")){
                result = line;
                Map<String,String> tokenMap = JSONObject.parseObject(line,Map.class);
                setToken(tokenMap.get("token"));
                TokenUtil.token = token;
            }
        }
        return result;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }
}
